/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.consumer.rebalance;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.rocketmq.client.consumer.AllocateMessageQueueStrategy;
import org.apache.rocketmq.common.message.MessageQueue;

/**
 * Computer room Hashing queue algorithm, such as Alipay logic room
 * 机房负载策略，其实这个策略就是当前Consumer只负载处在指定的机房内的MessageQueue，
 * 还有brokerName的命名必须要按要求的格式来设置：机房名@brokerName
 *
 * 机房分配现根据MQ中的brokerName找出有效的机房信息（也就是消息队列）。然后在评分，这个算法的逻辑是先算出平均值和余数，
 * 它和AllocateMessageQueueAveragely平均算法的不同在于，它是先给每个消费者分配mod（平均值个数）个消息队列，然后余数在从头开始一个个分配，
 * 假设mq有8个，消费者3个，那么平均值mod = 2，余数2，分配方式就是每个消费者先分配两个mq，{0，1},{2，3},{4，5}，然后余数2个在从头开始分配，
 * 最后就是{0，1，6},{2，3，7},{4，5}。
 */
public class AllocateMessageQueueByMachineRoom implements AllocateMessageQueueStrategy {

    private Set<String> consumeridcs;

   /* AllocateMessageQueueByMachineRoom allocateMachineRoom = new AllocateMessageQueueByMachineRoom();
    //指定机房名称  machine_room1、machine_room2
    allocateMachineRoom.setConsumeridcs(new HashSet<>(Arrays.asList("machine_room1","machine_room2")));
    //设置consumer的负载策略
    consumer.setAllocateMessageQueueStrategy(allocateMachineRoom);
    //启动consumer
    consumer.start();*/

    /**
     * 机房负载策略
     * 1. 首先赛选出当前Topic处在指定机房的队列
     * 2. 赛选出队列后，按照平均负载策略进行具体的分配（算法极其相似）
     * 其实这个策略就是对MessageQueue进行了过滤，过滤完了以后，后续操作就按照平均负载策略来进行具体负载操作。
     * @param consumerGroup current consumer group
     * @param currentCID    current consumer id
     * @param mqAll         message queue set in current topic
     * @param cidAll        consumer set in current consumer group
     * @return
     */
    @Override
    public List<MessageQueue> allocate(String consumerGroup, String currentCID, List<MessageQueue> mqAll,
        List<String> cidAll) {
        List<MessageQueue> result = new ArrayList<MessageQueue>();
        // 当前consumer的下标
        int currentIndex = cidAll.indexOf(currentCID);
        if (currentIndex < 0) {
            return result;
        }
        // 符合机房条件的队列
        List<MessageQueue> premqAll = new ArrayList<MessageQueue>();
        // 根据brokerName解析出所有有效的机房信息（有效mq）
        for (MessageQueue mq : mqAll) {
            // brokerName命名规则   machine_room1@broker-a
            String[] temp = mq.getBrokerName().split("@");
            // 判断是否符合指定的机房条件
            if (temp.length == 2 && consumeridcs.contains(temp[0])) {
                premqAll.add(mq);
            }
        }
        // 分配到的队列数
        int mod = premqAll.size() / cidAll.size();
        // 平均之后的余数
        int rem = premqAll.size() % cidAll.size();
        // 当前分配到的第一个队列索引
        int startIndex = mod * currentIndex;
        // 分配到的最后一个队列索引
        int endIndex = startIndex + mod;
        // 取startIndex到endIndex的队列
        // //所有消费者先平均分配，多的余数在依次分配，例如：队列8，消费者3，{0,1,6},{2,3,7},{4,5}
        for (int i = startIndex; i < endIndex; i++) {
            result.add(premqAll.get(i));
        }
        // MessageQueue数量和Consumer不是整数倍时 有点像平均分配因为队列下标取到的也是连续的
        if (rem > currentIndex) {
            result.add(premqAll.get(currentIndex + mod * cidAll.size()));
        }
        return result;
    }

    @Override
    public String getName() {
        return "MACHINE_ROOM";
    }

    public Set<String> getConsumeridcs() {
        return consumeridcs;
    }

    public void setConsumeridcs(Set<String> consumeridcs) {
        this.consumeridcs = consumeridcs;
    }
}
